package com.java110.mall.shop.bmo.shop.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountBondObjDto;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.shop.ShopAuditDto;
import com.java110.dto.shop.ShopCommunityDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IAccountBondObjInnerServiceSMO;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.goods.IDistributionModeInnerServiceSMO;
import com.java110.intf.shop.*;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.distributionMode.DistributionModePo;
import com.java110.po.shop.ShopPo;
import com.java110.po.shop.ShopAuditPo;
import com.java110.po.shop.ShopCommunityPo;
import com.java110.po.shop.ShopGoodsPo;
import com.java110.mall.shop.bmo.shop.IUpdateShopBMO;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("updateShopBMOImpl")
public class UpdateShopBMOImpl implements IUpdateShopBMO {

    public static final String STATE_Y = "1100"; // 同意
    public static final String STATE_N = "1200"; // 拒绝

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IShopCommunityInnerServiceSMO shopCommunityInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;


    @Autowired
    private IShopRangeRelInnerServiceSMO shopRangeRelInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IShopGoodsInnerServiceSMO shopGoodsInnerServiceSMOImpl;

    @Autowired
    private IShopAuditInnerServiceSMO shopAuditInnerServiceSMOImpl;
    @Autowired
    private IDistributionModeInnerServiceSMO distributionModeInnerServiceSMOImpl;
    @Autowired
    private IAccountBondObjInnerServiceSMO accountBondObjInnerServiceSMOImpl;

    /**
     * @param shopPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> update(ShopPo shopPo, DistributionModePo distributionModePo) {
        ShopDto shopDto = new ShopDto();
        shopDto.setShopName(shopPo.getShopName());
        shopDto.setStatusCd("0");
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (shopDtos.size() > 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败，店铺名称重复！");
        }
        if (shopDtos.size() == 1 && !shopDtos.get(0).getShopId().equals(shopPo.getShopId())) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败，店铺名称重复！");
        }
//        FileDto fileDto = new FileDto();
//        fileDto.setContext(shopPo.getShopLogo());
//        fileDto.setFileName(shopPo.getShopId());
//        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);
//        shopPo.setShopLogo(fileName);
        //处理商店状态
        dealShopState(shopPo);
        int flag = shopInnerServiceSMOImpl.updateShop(shopPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }
        //修改派送方式
        DistributionModeDto distributionModeDto = new DistributionModeDto();
        distributionModeDto.setShopId(shopPo.getShopId());
        distributionModeDto.setModeId(distributionModePo.getModeId());
        List<DistributionModeDto> distributionModeDtos = distributionModeInnerServiceSMOImpl.queryDistributionModes(distributionModeDto);
        if (!ListUtil.isNull(distributionModeDtos)) {
            DistributionModePo deleteDistributionModePo = new DistributionModePo();
            deleteDistributionModePo.setModeId(distributionModeDtos.get(0).getModeId());
            flag = distributionModeInnerServiceSMOImpl.deleteDistributionMode(deleteDistributionModePo);
            if (flag < 1) {
                return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "删除商品与配送方式关系失败");
            }
        }
        if (!"-1".equals(distributionModePo.getModeName())) {
            //处理商品与配送方式关系
            distributionModePo.setModeId(GenerateCodeFactory.getGeneratorId("11"));
            distributionModePo.setShopId(shopPo.getShopId());
            if ("100".equals(distributionModePo.getModeName())) {
                distributionModePo.setModeName("固定费");
                distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_STORE);
            } else {
                distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_USER);
            }
            distributionModePo.setbId("-1");
            flag = distributionModeInnerServiceSMOImpl.saveDistributionMode(distributionModePo);
            if (flag < 1) {
                return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存店铺配送方式失败");
            }
        }


        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");

    }

    private void dealShopState(ShopPo shopPo) {

        if (!ShopDto.STATE_APPLY.equals(shopPo.getState())) {
            return;
        }

        //判断是否缴了保证金
        AccountBondObjDto accountBondObjDto = new AccountBondObjDto();
        accountBondObjDto.setObjId(shopPo.getShopId());
        accountBondObjDto.setState(AccountBondObjDto.STATE_BUY_FINISH);
        List<AccountBondObjDto> accountBondObjDtos = accountBondObjInnerServiceSMOImpl.queryAccountBondObjs(accountBondObjDto);
        if (ListUtil.isNull(accountBondObjDtos)) {
            shopPo.setState(ShopDto.STATE_B);
        } else {
            shopPo.setState(ShopDto.STATE_F);
        }
    }

    /**
     * @param shopPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> updateAudit(ShopPo shopPo, ShopAuditPo shopAuditPo, DistributionModePo distributionModePo) {
        ShopDto shopDto = new ShopDto();
        shopDto.setShopName(shopPo.getShopName());
        shopDto.setStatusCd("0");
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (shopDtos.size() > 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败，店铺名称重复！");
        }
        if (shopDtos.size() == 1 && !shopDtos.get(0).getShopId().equals(shopPo.getShopId())) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败，店铺名称重复！");
        }
        shopDto.setShopId(shopPo.getShopId());
        shopDto.setShopName("");
        shopDto.setStatusCd("0");
        shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        //需要处理审核的地方 店铺名称、logo，商铺类型，开店类型，商铺描述，位置
        boolean _nameFlag = !shopDtos.get(0).getShopName().equals(shopPo.getShopName());
        //boolean _logoFlag = shopAuditPo.getChangeLogo().equals("1") ? true : false;
        boolean _openTypeFlag = !shopDtos.get(0).getOpenType().equals(shopPo.getOpenType());
        boolean _shopTypeFlag = !shopDtos.get(0).getShopType().equals(shopPo.getShopType());
        boolean _shopDescFlag = !shopDtos.get(0).getShopDesc().equals(shopPo.getShopDesc());
        boolean _sendFlag = !shopDtos.get(0).getSendAddress().equals(shopPo.getSendAddress());
        int flag;
        String msg = "";
        if (_nameFlag || _openTypeFlag || _shopTypeFlag || _shopDescFlag || _sendFlag) {//走审核
            ShopAuditDto shopAuditDto = new ShopAuditDto();
            shopAuditDto.setShopId(shopPo.getShopId());
            shopAuditDto.setStoreId(shopPo.getStoreId());
            shopAuditDto.setState(ShopDto.STATE_APPLY);
            int count = shopAuditInnerServiceSMOImpl.queryShopAuditsCount(shopAuditDto);
            if (count > 0) {
                return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "当前店铺已有待审核信息，请勿重复提交。");
            }
            shopAuditPo.setStoreId(shopDtos.get(0).getStoreId());
            shopAuditPo.setAuditId(GenerateCodeFactory.getGeneratorId("11"));
            shopAuditPo.setState(ShopDto.STATE_APPLY);//全部是新申请
            flag = shopAuditInnerServiceSMOImpl.saveShopAudit(shopAuditPo);
            msg = "含有需要审核的信息，审核通过后即可展示。";
        } else {//不做审核，直接更新
            flag = shopInnerServiceSMOImpl.updateShop(shopPo);
        }
        if (flag > 0) {
            //修改派送方式
            DistributionModeDto distributionModeDto = new DistributionModeDto();
            distributionModeDto.setShopId(shopPo.getShopId());
            distributionModeDto.setModeId(distributionModePo.getModeId());
            List<DistributionModeDto> distributionModeDtos = distributionModeInnerServiceSMOImpl.queryDistributionModes(distributionModeDto);
            if (!ListUtil.isNull(distributionModeDtos)) {
                DistributionModePo deleteDistributionModePo = new DistributionModePo();
                deleteDistributionModePo.setModeId(distributionModeDtos.get(0).getModeId());
                flag = distributionModeInnerServiceSMOImpl.deleteDistributionMode(deleteDistributionModePo);
                if (flag < 1) {
                    return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "删除商品与配送方式关系失败");
                }
            }
            if (!"-1".equals(distributionModePo.getModeName())) {
                //处理商品与配送方式关系
                distributionModePo.setModeId(GenerateCodeFactory.getGeneratorId("11"));
                distributionModePo.setShopId(shopPo.getShopId());
                if ("100".equals(distributionModePo.getModeName())) {
                    distributionModePo.setModeName("固定费");
                    distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_STORE);
                } else {
                    distributionModePo.setModeType(DistributionModeDto.MODE_TYPE_USER);
                }
                distributionModePo.setbId("-1");
                flag = distributionModeInnerServiceSMOImpl.saveDistributionMode(distributionModePo);
                if (flag < 1) {
                    return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存店铺配送方式失败");
                }
            }
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功，" + msg);
        }
        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    @Override
    @Java110Transactional
    public ResponseEntity<String> auditShop(JSONObject reqJson) {

        Assert.hasKeyAndValue(reqJson, "storeId", "未包含商户");
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺");
        Assert.hasKeyAndValue(reqJson, "userId", "未包含审核人");
        Assert.hasKeyAndValue(reqJson, "state", "未包含审核状态");
        Assert.hasKeyAndValue(reqJson, "remark", "未包含审核意见");

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "审核人不存在");
        ShopPo shopPo = new ShopPo();
        shopPo.setStoreId(reqJson.getString("storeId"));
        shopPo.setShopId(reqJson.getString("shopId"));

        if (STATE_Y.equals(reqJson.getString("state"))) {
            shopPo.setState(ShopDto.STATE_Y);
        } else if (STATE_N.equals(reqJson.getString("state"))) {
            shopPo.setState(ShopDto.STATE_N);
        } else {
            shopPo.setState(ShopDto.STATE_APPLY);
        }
        int flag = shopInnerServiceSMOImpl.updateShop(shopPo);
        if (flag < 1) {
            return ResultVo.error("审核失败");
        }
        return ResultVo.success();
    }

    @Override
    public ResponseEntity<String> auditShopCommunity(JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "scId", "未包含入驻信息");
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺");
        Assert.hasKeyAndValue(reqJson, "userId", "未包含审核人");
        Assert.hasKeyAndValue(reqJson, "state", "未包含审核状态");
        Assert.hasKeyAndValue(reqJson, "remark", "未包含审核意见");

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "审核人不存在");

        ShopCommunityPo shopCommunityPo = new ShopCommunityPo();
        ShopGoodsPo shopGoodsPo = new ShopGoodsPo();
        shopCommunityPo.setScId(reqJson.getString("scId"));
        shopCommunityPo.setShopId(reqJson.getString("shopId"));

        if ("1100".equals(reqJson.getString("state"))) {
            shopCommunityPo.setState(ShopCommunityDto.STATE_S);
            shopGoodsPo.setState(ShopCommunityDto.STATE_S);
        } else {
            shopCommunityPo.setState(ShopCommunityDto.STATE_F);
            shopGoodsPo.setState(ShopCommunityDto.STATE_F);
        }
        int flag = shopCommunityInnerServiceSMOImpl.updateShopCommunity(shopCommunityPo);
        shopGoodsPo.setScId(shopCommunityPo.getScId());
        shopGoodsPo.setShopId(shopCommunityPo.getShopId());
        shopGoodsInnerServiceSMOImpl.updateShopGoods(shopGoodsPo);
        if (flag < 1) {
            return ResultVo.error("审核失败");
        }
        return ResultVo.success();
    }

    @Override
    public ResponseEntity<String> bondEditShop(ShopPo shopPo) {

        int flag = shopInnerServiceSMOImpl.updateShop(shopPo);
        if (flag < 1) {
            return ResultVo.error("更新保证金状态失败");
        }
        return ResultVo.success();
    }
}
